import uuid

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from api import models
import jwt
import datetime
from api.extensions.auth import JwtQueryParamsAuthentication
from api.utils.jwt_auth import create_token

salt = 'abcfkghwkksh'


class LoginView(APIView):
    """用户登录"""

    def post(self, request, *args, **kwargs):
        user = request.data.get('username')
        pwd = request.data.get('password')

        print(request.data)

        print(user)
        print(pwd)

        user_object = models.UserInfo.objects.filter(
            username=user,
            password=pwd
        ).first()

        if not user_object:
            return Response({
                'code': 1000,
                'error': '用户名或密码错误'
            })

        random_string = str(uuid.uuid4())
        user_object.token = random_string
        user_object.save()

        return Response({
            'code': 1001,
            'data': random_string
        })


class OrderView(APIView):
    def get(self, request, *args, **kwargs):
        token = request.query_params.get('token')
        if not token:
            return Response({
                'code': 2000,
                'error': '登录成功之后才能访问'
            })

        user_object = models.UserInfo.objects.filter(token=token).first()

        if not user_object:
            return Response({
                'code': 2000,
                'error': 'token无效'
            })

        return Response('订单列表')


class JwtLoginView(APIView):
    """用户登录"""

    def post(self, request, *args, **kwargs):
        user = request.data.get('username')
        pwd = request.data.get('password')

        user_object = models.UserInfo.objects.filter(
            username=user,
            password=pwd
        ).first()

        if not user_object:
            return Response({
                'code': 1000,
                'error': '用户名或密码错误'
            })

        headers = {
            'typ': 'jwt',
            'alg': 'HS256'
        }

        payload = {
            'user_id': user_object.id,
            'username': user_object.username,
            'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=1)
        }

        token = jwt.encode(
            payload=payload,
            key=salt,
            algorithm='HS256',
            headers=headers
        )

        return Response({
            'code': 1001,
            'data': token
        })


class JwtOrderView(APIView):
    def get(self, request, *args, **kwargs):
        token = request.query_params.get('token')
        if not token:
            return Response({
                'code': 2000,
                'error': '登录成功之后才能访问'
            })

        payload = None
        msg = None

        try:
            payload = jwt.decode(token, salt, ['HS256'])
        except jwt.exceptions.ExpiredSignatureError:
            msg = 'token已经失效'
        except jwt.DecodeError:
            msg = 'token认证失败'
        except jwt.InvalidTokenError:
            msg = '非法的token'

        if not payload:
            return Response({
                'code': 1003,
                'error': msg
            })

        return Response({
            'code': 2000,
            'data': payload
        })

        # user_object = models.UserInfo.objects.filter(token=token).first()
        #
        # if not user_object:
        #     return Response({
        #         'code': 2000,
        #         'error': 'token无效'
        #     })
        #
        # return Response('订单列表')


class ProLoginView(APIView):
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        user = request.data.get('username')
        pwd = request.data.get('password')
        user_object = models.UserInfo.objects.filter(username=user, password=pwd).first()
        if not user_object:
            return Response({
                'code': 1000,
                'error': '用户名或密码错误'
            })
        token = create_token(
            {'id': user_object.id, 'name': user_object.username}
        )
        return Response({'code': 1001, 'data': token})


class ProOrderView(APIView):
    # authentication_classes = [JwtQueryParamsAuthentication]

    def get(self, request, *args, **kwargs):

        return Response(request.user)
